import OpenAI from 'openai';
import { registerHandler, setupMessageHandlers } from './message.main';
import { exec } from 'child_process';
import { app } from 'electron';
import { sendMessageV2 } from './event.send-message-v2';
import { execBash, execCopyPaste } from './event.execBash';

// const model = 'doubao-1.5-vision-pro-32k-250115'
const model = 'deepseek-v3-250324';

setupMessageHandlers();
registerHandler('send-message-v2', sendMessageV2);
registerHandler('bash-exec', execBash);
registerHandler('copy-paste', execCopyPaste);
registerHandler('send-message', async ({ messages, view }, continueCallback) => {
  const openai = new OpenAI({
    baseURL: 'https://ark.cn-beijing.volces.com/api/v3',
    apiKey: '572fd2fd-0cc0-443c-a278-6e5271d942ed',
  });

  const stream = await openai.chat.completions.create({
    messages: messages.map(({ role, content }) => ({ role, content })),
    // model: 'deepseek-v3-250324',
    model: model,
    stream: true,
  });

  let fullContent = '';
  for await (const result of stream) {
    const content = result.choices[0]?.delta?.content || '';
    fullContent += content;
    continueCallback(content);
  }

  if (view === 'content') {
    const regex = /```\w+\n([\s\S]*?)\n```/;
    const match = fullContent.match(regex);
    if (match) {
      const codeContent = match[1].trim(); // 获取匹配的代码内容
      if (codeContent) {
        // 复制代码到剪贴板
        // clipboard.writeText(codeContent);
        // 隐藏 app
        app.hide();
        // 执行粘贴
        // 模拟 Command+V
        setTimeout(() => {
          console.log(codeContent);
          exec(`osascript -e '
  set the clipboard to "${codeContent.replace(/"/g, '\\"')}"
  tell app "System Events" to keystroke "v" using command down
'`);
        }, 100);
      }
    }
    return null;
  }

  if (view !== 'chat') {
    return null;
  }

  const bashExecRegex = /```bash\.exec?\s*([^\n]*?)\s*```/g;
  let match;
  let limit = fullContent.startsWith('```bash.exec') && fullContent.endsWith('```');
  while ((match = bashExecRegex.exec(fullContent)) !== null && limit) {
    const command = match[1].trim();
    console.log(`执行命令：${command}`);
    let execResult;
    try {
      execResult = await executeCommand(command);
      execResult = `执行结果：成功\n${execResult}\n`;
    } catch (error) {
      execResult = `执行结果：失败\n${error.message}\n`;
    }
    continueCallback(execResult);
    console.log(execResult);
  }

  return null;
});

registerHandler('update-memory', async (messages) => {
  const openai = new OpenAI({
    baseURL: 'https://ark.cn-beijing.volces.com/api/v3',
    apiKey: '572fd2fd-0cc0-443c-a278-6e5271d942ed',
  });

  const resp = await openai.chat.completions.create({
    messages: messages.map((message) => {
      message = { ...message };
      delete message.contentArray;
      return message;
    }),
    // model: 'deepseek-v3-250324',
    model: model,
    stream: false,
  });

  const fullContent = resp.choices[0].message.content;
  return fullContent;
});

// 执行命令的函数（需要根据你的环境实现）
async function executeCommand(command) {
  // 这里需要根据你的客户端环境实现命令执行
  // 以下是 Node.js 环境的示例实现

  return new Promise((resolve, reject) => {
    exec(command, (error, stdout, stderr) => {
      if (error) {
        reject(new Error(stderr || error.message));
      } else {
        resolve(stdout.trim());
      }
    });
  });
}
